import React, { useState } from 'react';
import './styles.css';

interface Task {
  TaskID: string;
  productName: string;
  status: string;
  isTerminated?: boolean;
  canContinue?: boolean;
}

interface TaskListProps {
  title: string;
  tasks: Task[];
  showOption?: boolean;
  onTaskUpdate: (taskId: string, actionType: number) => void;
}

const TaskList: React.FC<TaskListProps> = ({ title, tasks, showOption = false, onTaskUpdate }) => {
  const [openDropdownIndex, setOpenDropdownIndex] = useState<number | null>(null);
  const [confirmDialog, setConfirmDialog] = useState<{
    show: boolean;
    taskId: string;
    action: string;
    actionType: number;
  }>({ show: false, taskId: '', action: '', actionType: -1 });

  const toggleDropdown = (index: number) => {
    if (openDropdownIndex === index) {
      setOpenDropdownIndex(null);
    } else {
      setOpenDropdownIndex(index);
    }
  };

  const getRowClassName = (status: string) => {
    switch (status) {
      case '待处理':
        return 'pending';
      case '处理中':
        return 'processing';
      case '已完成':
        return 'completed';
      default:
        return '';
    }
  };

  const handleActionConfirm = (taskId: string, action: string, actionType: number) => {
    if (actionType === 0 || actionType === 1) { // 取消或删除需要确认
      setConfirmDialog({
        show: true,
        taskId,
        action,
        actionType
      });
    } else {
      handleActionExecute(taskId, action, actionType);
    }
  };

  const handleActionExecute = async (taskId: string, action: string, actionType: number) => {
    try {
      // 模拟 POST 请求
      const response = await mockPostRequest(taskId, actionType);
      if (response.success) {
        console.log(`Task ${taskId}: ${action} successful`);
        // 调用父组件的更新函数
        onTaskUpdate(taskId, actionType);
      } else {
        console.error(`Task ${taskId}: ${action} failed`);
        // 这里可以添加错误处理逻辑，比如显示错误提示
      }
    } catch (error) {
      console.error(`Error executing ${action} for task ${taskId}:`, error);
      // 这里可以添加错误处理逻辑，比如显示错误提示
    }
    setConfirmDialog({ show: false, taskId: '', action: '', actionType: -1 });
  };

  // 模拟 POST 请求的函数
  const mockPostRequest = async (taskId: string, actionType: number) => {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟请求成功
    return {
      success: true,
      data: {
        taskId,
        actionType,
        message: 'Operation successful'
      }
    };
  };

  const renderActionButton = (task: Task) => {
    if (task.status === '已完成' && !task.canContinue) return null;
    
    if (task.status === '已完成' && task.canContinue) {
      return (
        <div className="action-buttons">
          <button 
            className="action-button continue"
            onClick={() => handleActionConfirm(task.TaskID, '继续处理', 3)}
          >
            继续处理
          </button>
        </div>
      );
    }
    
    return (
      <div className="action-buttons">
        {task.status === '待处理' && (
          <button 
            className="action-button cancel"
            onClick={() => handleActionConfirm(task.TaskID, '取消', 0)}
          >
            取消
          </button>
        )}
        {task.status === '处理中' && (
          <button 
            className="action-button terminate"
            onClick={() => handleActionConfirm(task.TaskID, '终止', 1)}
          >
            终止
          </button>
        )}
        <button 
          className="action-button delete"
          onClick={() => handleActionConfirm(task.TaskID, '删除', 2)}
        >
          删除
        </button>
      </div>
    );
  };

  return (
    <div className="task-list-container">
      <div className="task-list-header">
        <h2>{title}</h2>
        <div className="task-header">
          <span className="task-id">TaskID</span>
          <span className="product-name">品名</span>
          {!showOption && <span className="status">状态</span>}
          {showOption && (
            <span className="option">
              操作
            </span>
          )}
          {!showOption && <span className="action">操作</span>}
        </div>
      </div>
      <div className="task-list">
        {tasks.map((task, index) => (
          <div 
            key={task.TaskID} 
            className={`task-row ${getRowClassName(task.status)} ${task.isTerminated ? 'terminated' : ''} fade-move`}
          >
            <span className={`task-id ${task.isTerminated ? 'terminated-id' : ''}`}>{task.TaskID}</span>
            <span className="product-name">{task.productName}</span>
            {!showOption && <span className="status">{task.status}</span>}
            {showOption && (
              <span className="option">
                {task.canContinue && (
                  <button 
                    className="action-button continue"
                    onClick={() => handleActionConfirm(task.TaskID, '继续处理', 3)}
                  >
                    继续处理
                  </button>
                )}
                <button 
                  className="option-button" 
                  onClick={() => toggleDropdown(index)}
                >
                  Option ▼
                </button>
                {openDropdownIndex === index && (
                  <div className="dropdown-menu">
                    <button className="dropdown-item">下载图片</button>
                    <button className="dropdown-item">查看prompt</button>
                  </div>
                )}
              </span>
            )}
            {!showOption && <span className="action">{renderActionButton(task)}</span>}
          </div>
        ))}
      </div>
      {/* 确认对话框 */}
      {confirmDialog.show && (
        <div className="confirm-dialog-overlay">
          <div className="confirm-dialog">
            <h3>确认{confirmDialog.action}？</h3>
            <p>您确定要{confirmDialog.action}该任务吗？</p>
            <div className="confirm-dialog-buttons">
              <button 
                className="confirm-button"
                onClick={() => handleActionExecute(
                  confirmDialog.taskId, 
                  confirmDialog.action,
                  confirmDialog.actionType
                )}
              >
                确认
              </button>
              <button 
                className="cancel-button"
                onClick={() => setConfirmDialog({ 
                  show: false, 
                  taskId: '', 
                  action: '',
                  actionType: -1 
                })}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TaskList; 